import importlib
import threading
import time
import traceback

import win32api
import win32con
import win32gui
from PyQt5.QtWidgets import QApplication
from pynput.keyboard import KeyCode, Key
from moni.hook_key_mouse import HookKeyMouse
from moni.moni import MoNiInterface,MoNi
from tools.utils import is_color, window_set_activate
from tools.screenshot import screenshot
import setting
class AutoTFT(HookKeyMouse):
    def __init__(self, moni: MoNiInterface):
        super().__init__(hookKey=True, hookMouse=False)
        self.is_runing=False
        self.is_pause=False
        self.moni=moni
        self.screen=None
        self.sg=None
    def set_sg(self,sg):
        self.sg=sg
    def on_release(self, key):
        if key == KeyCode.from_char('`'):
            if self.is_runing:
                self.sg.show_log.emit("关闭拿牌模式",(255,0,0),2000)
                self.is_runing=False
            else:
                self.sg.show_log.emit("开启拿牌模式",(255,255,0),2000)
                self.is_runing=True
                threading.Thread(target=self.run,daemon=True).start()
        elif key == Key.home:
            self.sg.hide_ui.emit()
        elif key == Key.up:
            #取到当前窗口句柄
            hwnd = win32gui.GetForegroundWindow()
            if hwnd==self.moni.hwnd:
                self.sg.switch_id.emit(False)
        elif key == Key.down:
            hwnd = win32gui.GetForegroundWindow()
            if hwnd == self.moni.hwnd:
                self.sg.switch_id.emit(True)
    def bind(self,hwnd):
        self.moni.bind(hwnd)
    def should_click(self):
        '''
        判断是否应该点击
        :return: 返回 -1 -2 -3  代表没有找到  0代表第一个 1代表第二个 以此类推
        '''

        self.screen=self.get_screen()
        if self.screen is None or self.moni.hwnd==0:
            return -3
        is_ok=True
        #先判断当前是否为购买棋子的界面
        for p in setting.prod_box_pos_list:
            color_bgr = self.screen[p['y'], p['x']]
            color_rgb = [color_bgr[2], color_bgr[1], color_bgr[0]]
            #print(p['x'],p['y'],color_rgb,setting.prod_box_color)
            if not is_color(color_rgb, setting.prod_box_color, tolerance=40):
                is_ok=False
        if not is_ok:
            return -2
        #判断商品区域哪个是推荐的
        for i,prod_area in enumerate( setting.prod_area_list):
            for p in prod_area:
                color_bgr = self.screen[p['y'], p['x']]
                color_rgb = [color_bgr[2], color_bgr[1], color_bgr[0]]

                if not is_color(color_rgb,setting.prod_color,tolerance=20):
                    #判断是否买得起
                    color_bgr = self.screen[setting.prod_gold['y'], setting.prod_gold['x']+sum(setting.prod_area_steps[:i])]
                    color_rgb = [color_bgr[2], color_bgr[1], color_bgr[0]]

                    #print(setting.prod_gold['y'], setting.prod_gold['x']+ setting.prod_area_step * i,color_rgb,setting.prod_gold["color"])
                    if is_color(color_rgb, setting.prod_gold["color"], tolerance=50):
                        return i



        #判断是否是扎克组织细胞
        for i in range(5):
            is_ok=True
            for prod_zack in setting.prod_zack_list:
                x=prod_zack['x']+sum(setting.prod_area_steps[:i])
                y=prod_zack['y']
                color_bgr = self.screen[y, x]
                color_rgb = [color_bgr[2], color_bgr[1], color_bgr[0]]
                #print(i ,x, y,color_rgb,prod_zack["color"])
                if not is_color(color_rgb, prod_zack["color"], tolerance=45):
                    #只要有一个颜色不对 就不是
                    is_ok=False
                    break
            if is_ok:
                return i

        return -1
    def get_screen(self):
        return screenshot(self.moni.hwnd, 0, 0, self.moni.window_width, self.moni.window_height)
    def click_prod(self,index=0):
        '''
        点击商品
        :param index: 商品的索引 0代表第一个 1代表第二个 以此类推
        :return:
        '''

        if index<0 or index>=5 :
            print(index)
            return False
        window_set_activate(self.moni.hwnd)
        self.moni.mouse_left_click(setting.prod_click_pos_list[index]['x'],setting.prod_click_pos_list[index]['y'],0.01)
        time.sleep(0.2)
        #判断是否购买成功prod_color
        self.screen = self.get_screen()
        for p in setting.prod_area_list[index]:
            color_bgr = self.screen[p['y'], p['x']]
            color_rgb = [color_bgr[2], color_bgr[1], color_bgr[0]]
            #print(p['x'],p['y'],color_rgb,setting.prod_color)
            #如果发现有一个颜色不一样  说明没有买成功还是属于提醒状态
            if not is_color(color_rgb, setting.prod_color, tolerance=40):
                return False
        return  True
    def click_confirmed(self):
        if self.get_game_hwnd()==0:

            return
        window_set_activate(self.moni.hwnd)
        for i,pos in enumerate(setting.xiaodui_bt_pos):
            time.sleep(0.4)
            self.moni.mouse_left_click(pos['x'], pos['y'], 0.05)
            # self.moni.mouse_left_click(pos['x'], pos['y'], 0.01)
    def get_game_hwnd(self):
        hwnd=win32gui.FindWindow(setting.GAME_CLASS, setting.GAME_TITLE)
        print("FindWindow 返回:", hex(hwnd))
        if hwnd!=0:
            importlib.reload(setting)  # 强制重新加载
            print("reload 后 window_width =", setting.window_width)
            if setting.window_width>=640:
                self.bind(hwnd)
                return hwnd
            else:
                return 0


        return 0
    def run(self):
        num_err=0
        self.is_runing=True
        while True:

            if not self.is_runing:
                return

            # if self.is_pause:
            #     time.sleep(0.5)
            #     continue
            try:
                index = self.should_click()

                if index >= 0 :
                    _ret=self.click_prod(index)
                    if _ret:
                        num_err=0
                    else:

                        num_err+=1
                        if num_err>=2:
                            self.is_runing = False
                            self.sg.show_log.emit("提醒:目前已关闭自动拿牌 按~键恢复", (255, 0, 0),20000)
                            return
                        else:
                            time.sleep(0.3)

                elif index ==-3:

                    time.sleep(2)
                    self.get_game_hwnd()
                else:
                    time.sleep(0.2)
            except :
                print(traceback.format_exc())
                time.sleep(2)
                self.get_game_hwnd()

if __name__ == '__main__':
    moni =MoNi().create( 2559938,2)
    auto_tft=AutoTFT(moni)
    auto_tft.get_game_hwnd(2559938)
    # 启动全局钩子
    HookKeyMouse.start_global_hook()
    auto_tft.run()

    while True:
        time.sleep(1)










